﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace CrabSS_Lite
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public string time = DateTime.Now.ToLocalTime().ToString();
        public MainWindow()
        {
            InitializeComponent();
            TextRange format = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
            format.Text = "开服就用CrabSS！\n程序全程离线运行，放心使用。\n一个Bug：生成的启动文件中的Xmx那里少了个-，更改代码无效，请手动进行更改\r";
            if (File.Exists("eula.txt"))
            {
                generateEULA.Content = "eula已经生成过了";
                generateEULA.IsEnabled = false;
            }
        }
        #region 5.0 生成随机字符串 + static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
        ///<summary>
        ///生成随机字符串 
        ///</summary>
        ///<param name="length">目标字符串的长度</param>
        ///<param name="useNum">是否包含数字，1=包含，默认为包含</param>
        ///<param name="useLow">是否包含小写字母，1=包含，默认为包含</param>
        ///<param name="useUpp">是否包含大写字母，1=包含，默认为包含</param>
        ///<param name="useSpe">是否包含特殊字符，1=包含，默认为不包含</param>
        ///<param name="custom">要包含的自定义字符，直接输入要包含的字符列表</param>
        ///<returns>指定长度的随机字符串</returns>
        public static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
        {
            byte[] b = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
            Random r = new Random(BitConverter.ToInt32(b, 0));
            string s = null, str = custom;
            if (useNum == true) { str += "0123456789"; }
            if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
            if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
            if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
            for (int i = 0; i < length; i++)
            {
                s += str.Substring(r.Next(0, str.Length - 1), 1);
            }
            return s;
        }
        #endregion
        private void download_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Process.Start("https://www.mcbbs.net/forum.php?mod=viewthread&tid=1258095&page=1");
        }
        public Process p = new Process();
        private void generateEULA_Click(object sender, RoutedEventArgs e)
        {
            FileStream fs = File.Create("eula.txt");// 创建eula
            string eula = "eula=true";
            byte[] eulaB = System.Text.Encoding.Default.GetBytes(eula);
            fs.Write(eulaB, 0, eulaB.Length);
            fs.Close();
            generateEULA.Content = "eula生成成功";
            generateEULA.IsEnabled = false;
            return;
        }

        private void START_Click(object sender, RoutedEventArgs e)
        {
            if(bungee.IsChecked == true)
            {
                try
                {
                    DispatcherTimer timer = new DispatcherTimer();
                    string result = GetRandomString(5, true, true, true, false, "temp");
                    string cmd = "temp_start_" + result + ".cmd";
                    FileStream fs = File.Create(cmd);
                    string eula = "@echo off\n注意：您已激活BungeeCord模式，将忽略所有内存设置\njava -jar start.jar\npause";
                    byte[] eulaB = System.Text.Encoding.Default.GetBytes(eula);
                    fs.Write(eulaB, 0, eulaB.Length);
                    fs.Close();
                    var path = Environment.SystemDirectory;
                    TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
                    tr.Text = "\r[" + time + "]服务器正在启动\r";
                    p.StartInfo.FileName = cmd;
                    p.StartInfo.Arguments = cmd;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.CreateNoWindow = true;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardInput = true;
                    p.StartInfo.RedirectStandardError = true;
                    p.Start();
                    p.BeginOutputReadLine();
                    p.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("你想啥呢你", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
                    tr.Text = "\r[" + time + "]错误：" + ex.ToString() + " 在 System.MainWindow.p.Start 中\r";
                }
            }
            else
            {
                if (min.Text != "最小内存" && max.Text != "最大内存")
                {
                    try
                    {
                        DispatcherTimer timer = new DispatcherTimer();
                        string result = GetRandomString(5, true, true, true, false, "temp");
                        string cmd = "temp_start_" + result + ".cmd";
                        FileStream fs = File.Create(cmd);
                        string eula = "java -Xms" + min.Text + "m -Xmx" + max.Text + "m -jar start.jar\npause";
                        byte[] eulaB = System.Text.Encoding.Default.GetBytes(eula);
                        fs.Write(eulaB, 0, eulaB.Length);
                        fs.Close();
                        var path = Environment.SystemDirectory;
                        TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
                        tr.Text = "\r[" + time + "]服务器正在启动\r";
                        p.StartInfo.FileName = cmd;
                        p.StartInfo.Arguments = cmd;
                        p.StartInfo.UseShellExecute = false;
                        p.StartInfo.CreateNoWindow = true;
                        p.StartInfo.RedirectStandardOutput = true;
                        p.StartInfo.RedirectStandardInput = true;
                        p.StartInfo.RedirectStandardError = true;
                        p.Start();
                        p.BeginOutputReadLine();
                        p.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("你想啥呢你", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
                        tr.Text = "\r[" + time + "]错误：" + ex.ToString() + " 在 System.MainWindow.p.Start 中\r";
                    }
                }
                else if (min.Text == "最小内存")
                {
                    MessageBox.Show("你想啥呢你", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
                    tr.Text = "\r[" + time + "]错误：你想啥呢你 ***关键数据缺失*** 在 System.MainWindow.min.Text 中\r";
                }
                else if (max.Text == "最大内存")
                {
                    MessageBox.Show("你想啥呢你", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
                    tr.Text = "\r[" + time + "]错误：你想啥呢你 ***关键数据缺失*** 在 System.MainWindow.max.Text 中\r";
                }
                else
                {
                    MessageBox.Show("你想啥呢你", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
                    tr.Text = "\r[" + time + "]错误：你想啥呢你 ***关键数据缺失*** 在 System.MainWindow.min.Text 中\r";
                }
            }
        }
        private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
        {
            try
            {
                Action methodDelegate = delegate ()
                {
                    if (!String.IsNullOrEmpty(outLine.Data))
                    {
                        TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
                        tr.Text = "\r[" + time + "]" + outLine.Data + "\r";
                        Brush brush = Brushes.Black;
                        brush = Brushes.Black;
                        tr.ApplyPropertyValue(TextElement.ForegroundProperty, brush);
                        this.console_box.ScrollToEnd();
                    }
                };
                this.Dispatcher.BeginInvoke(methodDelegate);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "发生错误",MessageBoxButton.OK,MessageBoxImage.Hand);
            }
        }

        private void restart_Click(object sender, RoutedEventArgs e)
        {
            TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
            try
            {
                tr.Text = "\r[" + time + "]正在硬关闭服务器\r";
                p.Kill();
                p.CancelOutputRead();
                tr.Text = "\r[" + time + "]关闭完成。\r";
                try
                {
                    DispatcherTimer timer = new DispatcherTimer();
                    string result = GetRandomString(5, true, true, true, false,"");
                    string FileName = "temp_start_" + result + ".cmd";
                    FileStream fs = File.Create(FileName);
                    string f = "java -Xms"+min.Text+"m -Xmx"+max.Text+" -jar start.jar";
                    byte[] fB = System.Text.Encoding.Default.GetBytes(f);
                    fs.Write(fB, 0, fB.Length);
                    fs.Close();
                    var path = Environment.SystemDirectory;
                    string cmd = FileName;
                    tr.Text = "\r[" + time + "]服务器正在启动\r";
                    p.StartInfo.FileName = cmd;
                    p.StartInfo.Arguments = cmd;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.CreateNoWindow = true;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardInput = true;
                    p.StartInfo.RedirectStandardError = true;
                    p.Start();
                    p.BeginOutputReadLine();
                    p.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("你想啥呢你", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    tr.Text = "\r[" + time + "]重新启动时发生错误：" + ex.ToString() + "\r";
                }
            }
            catch (Exception ex)
            {
                tr.Text = "\r[" + time + "]关闭时发生错误："+ex.ToString()+"\r";
            }            
        }

        private void stop_Click(object sender, RoutedEventArgs e)
        {
            TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
            try
            {
                tr.Text = "\r[" + time + "]正在硬关闭服务器\r";
                Process.Start(@"C:\Windows\system32\taskkill.exe","-f -im java.exe");
                p.CancelOutputRead();
                tr.Text = "\r[" + time + "]关闭完成。\r";
            }
            catch (Exception ex)
            {
                tr.Text = "\r[" + time + "]关闭时发生错误：" + ex.ToString() + "\r";
            }
        }

        private void copy_core_Click(object sender, RoutedEventArgs e)
        {
            TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
            if(bungee.IsChecked == true)
            {
                try
                {
                    var of = new Microsoft.Win32.OpenFileDialog();
                    of.Filter = "核心文件 (*.jar)|*.jar";
                    if (of.ShowDialog() == true)
                    {
                        string corePath = System.IO.Path.GetFullPath(of.FileName);
                        string coreName = of.SafeFileName;
                        File.Copy(corePath, Environment.CurrentDirectory + "\\start.jar");
                        tr.Text = "\r[" + time + "]核心复制完成：" + coreName + "\r";
                    }
                }
                catch (Exception ex)
                {
                    tr.Text = "\r[" + time + "]载入时发生错误：" + ex.ToString() + "\r";
                }
            }
            else
            {
                try
                {
                    var of = new Microsoft.Win32.OpenFileDialog();
                    of.Filter = "核心文件 (*.jar)|*.jar";
                    if (of.ShowDialog() == true)
                    {
                        string corePath = System.IO.Path.GetFullPath(of.FileName);
                        string coreName = of.SafeFileName;
                        File.Copy(corePath, Environment.CurrentDirectory + "\\start.jar");
                        tr.Text = "\r[" + time + "]核心复制完成：" + coreName + "\r";
                    }
                }
                catch (Exception ex)
                {
                    tr.Text = "\r[" + time + "]载入时发生错误：" + ex.ToString() + "\r";
                }
            }
        }

        private void send_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                p.StandardInput.WriteLine(command.Text);
                p.StandardInput.AutoFlush = true;
            }
            catch(Exception ex)
            {
                TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
                tr.Text = "\r[" + time + "]执行时发生错误：" + ex.ToString() + "\r";
            }
        }

        private void sort_shutdown_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                p.StandardInput.WriteLine("stop");
                p.StandardInput.AutoFlush = true;
            }
            catch (Exception ex)
            {
                TextRange tr = new(console_box.Document.ContentEnd, console_box.Document.ContentEnd);
                tr.Text = "\r[" + time + "]执行时发生错误：" + ex.ToString() + "\r";
            }
        }

        private void Bungee_Checked(object sender, RoutedEventArgs e)
        {
            if (bungee.IsChecked == true)
            {
                min.IsEnabled = false;
                max.IsEnabled = false;
                restart.IsEnabled = false;
            }
            else
            {
                min.IsEnabled = true;
                max.IsEnabled = true;
                restart.IsEnabled = true;
            }
        }
    }
}
